package com.ld.security.common.mybatis.base.mapping;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ld.security.common.core.base.ESuperEntity;
import com.ld.security.common.core.util.GenericUtil;
import com.ld.security.common.core.util.ReflectionUtil;
import com.ld.security.common.core.util.StringUtil;
import com.ld.security.common.core.util.UuidUtil;
import com.ld.security.common.mybatis.base.po.IdPo;
import com.ld.security.common.mybatis.core.wrapper.EntityWrapper;

import java.util.Date;
import java.util.List;

/**
 * 基本dao接口
 * @param <E>
 */
public interface SuperMapping<E extends ESuperEntity> extends BaseMapper<E> {



    default Page<E> page(QueryWrapper ew, Page<E> page){
        this.selectPage(page,ew);

        return page;
    }

    default E getOne(QueryWrapper<E> ew){
        E e =  this.selectOne(ew);
        return  e;
    }

    default List<E> all(QueryWrapper<E> ew){
        List<E> list =   this.selectList(ew);
//        for (E e :list) {
//            CrptUtil.decrpt(e);
//        }
        return  list;
    }

    default int count(QueryWrapper<E> ew){
        return  this.selectCount(ew);
    }


    default int save(E entity){

        entity.setUptTime(new Date());

        int total = 0;
        String id = entity.getId();
        if(StringUtil.isNull(id)){
            entity.setId(UuidUtil.getId());
            entity.setCrtTime(new Date());
            ReflectionUtil.fill(entity);
            total = this.insert(entity);
        }else{
            QueryWrapper ew =  EntityWrapper.of(new IdPo(id));
            int v = this.count(ew);

            if(v == 0){

                entity.setCrtTime(new Date());
                ReflectionUtil.fill(entity);
                total = this.insert(entity);
            }else{
                entity.setUptTime(new Date());
                total = this.updateById(entity);
            }
        }
        return total;
    }


    default int remove(QueryWrapper<E> ew){
        return this.delete(ew);
    }

    default Class<E> getEntityClass()
    {
        return (Class<E>) GenericUtil.getGeneric(this.getClass(), SuperMapping.class, 0);
    }

}
